import datetime
import json

from django.shortcuts import render

from django.utils.decorators import method_decorator
from django.views import View
from django.http import JsonResponse, HttpResponse

import os

from homes import models
from order.models import Order
from users.models import User

os.environ
os.environ.setdefault(
    'DJANGO_SETTINGS_MODULE',
    'ihome.settings'
)
from django.conf import settings
from homes.models import Area, House, HouseImage, Facility

# 城区列表展示
from utils.views import login_required, QiniuUpload


# 城区列表
class Areas(View):

    def get(self, request):

        # 定义空列表
        area_list = []

        areas = Area.objects.all()

        for area in areas:
            area_list.append({
                'aid': area.id,
                'aname': area.name
            })

        return JsonResponse({
            'errno': 0,
            'errmsg': '获取成功',
            'data': area_list
        })



# 发布/搜索房源
class Houses(View):

    # 发布房源
    @method_decorator(login_required)
    def post(self, request):
        '''发布房源'''

        # 提取参数
        data = json.loads(request.body.decode())

        user = request.user

        title = data.get('title')
        price = data.get('price')
        area_id = data.get('area_id')
        address = data.get('address')
        room_count = data.get('room_count')
        acreage = data.get('acreage')
        unit = data.get('unit')
        capacity = data.get('capacity')
        beds = data.get('beds')
        deposit = data.get('deposit')
        min_days = data.get('min_days')
        max_days = data.get('max_days')
        facility = data.get('facility')

        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days, facility]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少参数'})

        try:
            house = House.objects.create(
                title = title,
                price = price,
                address = address,
                room_count = room_count,
                acreage = acreage,
                unit = unit,
                capacity = capacity,
                beds = beds,
                deposit = deposit,
                min_days = min_days,
                max_days = max_days,
                area_id = area_id,
                user_id = user.id
            )
            house.facility.set(facility)

        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '新增房屋失败'})


        return JsonResponse({'errno': 0 ,
                             'errmsg': '发布成功',
                             'data': {
                                 'house_id': house.id
                                }
                            })


    # 房源搜索
    def get(self, request):

        user = request.user

        aid = request.GET.get('aid')
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_key = request.GET.get('sk')
        page = request.GET.get('p')


        # 构建空列表
        house_list = []

        # 查询选中城区的房源对象

        if not aid:
            all_houses = House.objects.all()
            if not start_day:   # 城区和入住时间都未选中时

                for house in all_houses:
                    user_id = house.user_id
                    user = User.objects.get(id=user_id)
                    # 获取城区对象
                    area = Area.objects.get(id=house.area_id)

                    house_list.append({
                        'address': house.address,
                        'area_name': area.name,
                        'ctime': house.create_time,
                        'house_id': house.id,
                        "img_url": settings.QINIU_URL + house.index_image_url,
                        "order_count": house.order_count,
                        "price": house.price,
                        "room_count": house.room_count,
                        "title": house.title,
                        "user_avatar": settings.QINIU_URL + str(user.avatar)
                    })

            else:   # 选中入住时间却未选中城区市

                for house in all_houses:
                    house_id = house.id
                    room_count = house.room_count
                    user_id = house.user_id
                    user = User.objects.get(id=user_id)

                    # 获取城区对象
                    area = Area.objects.get(id=house.area_id)

                    # 获取订单对象，查询房源选中的入住日期当天进行中的订单总数
                    orders = Order.objects.filter(status__in=[1, 2],
                                                  begin_date__lte=start_day,
                                                  end_date__gte=start_day,
                                                  house_id=house_id).count()

                    # 判断房源是否已满
                    if orders >= room_count:
                        continue

                    house_list.append({
                        'address': house.address,
                        'area_name': area.name,
                        'ctime': house.create_time,
                        'house_id': house.id,
                        "img_url": settings.QINIU_URL + house.index_image_url,
                        "order_count": house.order_count,
                        "price": house.price,
                        "room_count": house.room_count,
                        "title": house.title,
                        "user_avatar": settings.QINIU_URL + str(user.avatar)
                    })

            return JsonResponse({'errno': 0,
                                 'errmsg': '请求成功',
                                 'data': {'houses': house_list},
                                 'total_page': page
                                 })


        all_houses = House.objects.filter(area_id=aid)

        # 未选择日期则显示全部
        if not start_day:
            for house in all_houses:
                user_id = house.user_id
                user = User.objects.get(id=user_id)
                # 获取城区对象
                area = Area.objects.get(id=house.area_id)

                house_list.append({
                    'address': house.address,
                    'area_name': area.name,
                    'ctime': house.create_time,
                    'house_id': house.id,
                    "img_url": settings.QINIU_URL + house.index_image_url,
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": settings.QINIU_URL + str(user.avatar)
                })

        else:   # 选中入住时间
            for house in all_houses:
                house_id = house.id
                room_count = house.room_count
                user_id = house.user_id
                user = User.objects.get(id=user_id)

                # 获取城区对象
                area = Area.objects.get(id=house.area_id)

                # 获取订单对象，查询房源选中的入住日期当天进行中的订单总数
                orders = Order.objects.filter(status__in=[1,2],
                                                begin_date__lte=start_day,
                                                end_date__gte=start_day,
                                                house_id=house_id).count()

                # 判断房源是否已满
                if orders >= room_count:
                    continue

                house_list.append({
                    'address': house.address,
                    'area_name':  area.name,
                    'ctime': house.create_time,
                    'house_id': house.id,
                    "img_url": settings.QINIU_URL + house.index_image_url,
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": settings.QINIU_URL + str(user.avatar)
                })

        return JsonResponse({'errno': 0,
                             'errmsg': '请求成功',
                             'data': {'houses':house_list},
                             'total_page': page
                             })





# 上传房源图片
class AddHouseImg(View):

    # 上传房源图片
    def post(self, request, house_id):


        # 获取用户上传图片对象
        img = request.FILES.get('house_image')

        # 获取图片二进制内容
        img_data = img.file.read()

        # 构建文件名
        file_name = str(house_id) + '_' + datetime.datetime.now().strftime("%Y%m%d%H%M%S")

        # 把图片信息文件写入到本地文件中
        try:
            with open('ihome/uploads/' + file_name, 'wb') as f:
                f.write(img_data)

        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4302, 'errmsg': '上传图片失败'})

        # 拼接上传目标文件路径
        img_file = settings.BASE_DIR + '/ihome/uploads/' + file_name

        index_image_url = QiniuUpload(house_id, img_file)

        # 删除上传到本地的临时文件
        os.remove(settings.BASE_DIR + '/ihome/uploads/' + file_name)

        try:
            house = House.objects.get(id=house_id)
            house.index_image_url = index_image_url
            house.save()

            # 图片连接存入数据库
            house_img = HouseImage.objects.create(
                url = index_image_url,
                house_id = house_id
            )

        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4001, 'errmsg': '上传图片失败'})

        # 构建响应数据
        url = settings.QINIU_URL + index_image_url
        return JsonResponse({'errno': 0,
                             'errmsg': '图片上传成功',
                             'data':{
                                 'url': url
                             }})


# 首页房屋推荐
class IndexHouse(View):

    # 房屋推荐
    def get(self, request):

        houses = House.objects.order_by('price')[:5]

        # 创建空列表
        houses_list = []

        for house in houses:

            houses_list.append({
                'house_id': house.id,
                'img_url': settings.QINIU_URL + house.index_image_url,
                'title': house.title
            })


        return JsonResponse({
            'errno': 0,
            'errmsg': 'ok',
            'data': houses_list
        })


# 房屋详情页
class HouseDetails(View):

    # 房屋详情
    def get(self, request, house_id):

        # 定义空列表
        house_list = []

        house = House.objects.get(id=house_id)

        # 获取设施对象
        facilities = house.facility.all()
        # 定义空列表，存储设施详情
        facility_list = []
        for facility in facilities:
            facility_list.append(facility.id)
        # print(facility_list)
        # 获取订单对象
        orders = Order.objects.filter(house_id=house.id)
        # 定义空列表，存储评论详情
        comment_list = []
        for order in orders:
            c_user = User.objects.get(id=order.user_id)
            comment_list.append({
                'comment': order.comment,
                'ctime': order.create_time,
                'user_name': c_user.username
            })
        a = comment_list

        # 定义空列表存储图片链接数据
        img_list = []
        imgs = HouseImage.objects.filter(house_id=house.id)

        for img in imgs:
            img_url = settings.QINIU_URL + img.url
            img_list.append(img_url)
            # print(img.url)

        h_user = User.objects.get(id=house.user_id)
        avatar_url = settings.QINIU_URL + str(h_user.avatar)

        user = request.user

        data = {
            "house": {
            "acreage": house.acreage,
            "address": house.address,
            "beds": house.beds,
            "capacity": house.capacity,
            "comments": comment_list,
            "deposit": house.deposit,
            "facilities": facility_list,
            "house_id": house.id,
            "img_urls": img_list,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.unit,
            "user_avatar": avatar_url,
            "user_id": h_user.id,
            "user_name": h_user.username
        },
                'user_id': user.id}

        return JsonResponse({
            'errno': 0,
            'errmsg': 'ok',
            'data': data
        })



















